﻿using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;

namespace ImportDataUtil
{
    public class ParaPersistant
    {
        private string binfile;
        private byte[] KEY;
        private byte[] IV;

        IFormatter formatter;


        public ParaPersistant(string file)
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //

            binfile = file;
            formatter = new BinaryFormatter();
            KEY = new byte[] { 59, 234, 235, 28, 90, 195, 186, 61, 94, 12, 108, 56, 63, 42, 111, 102, 241, 1, 186, 97, 49, 196, 253, 238, 186, 98, 87, 143, 102, 240, 59, 70 };
            IV = new byte[] { 134, 96, 42, 208, 242, 87, 2, 136, 59, 117, 212, 63, 72, 171, 130, 61 };

        }


        public void Write(ref Hashtable para)
        {
            Stream fs = new FileStream(binfile, FileMode.Create, FileAccess.Write, FileShare.None);
            RijndaelManaged RMCrypto = new RijndaelManaged();
            CryptoStream csEncrypt = new CryptoStream(fs, RMCrypto.CreateEncryptor(KEY, IV), CryptoStreamMode.Write);
            formatter.Serialize(csEncrypt, para);
            csEncrypt.Close();
            fs.Close();
        }
        public bool Write(object para)
        {

            try
            {
                Stream fs = new FileStream(binfile, FileMode.Create, FileAccess.Write, FileShare.None);
                RijndaelManaged RMCrypto = new RijndaelManaged();
                CryptoStream csEncrypt = new CryptoStream(fs, RMCrypto.CreateEncryptor(KEY, IV), CryptoStreamMode.Write);
                formatter.Serialize(csEncrypt, para);
                csEncrypt.Close();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog.AppendErrorMsg(ex.ToString());
                return false;
            }

        }

        public Hashtable Read()
        {
            Hashtable para;
            para = new Hashtable();

            try
            {
                Stream fs = new FileStream(binfile, FileMode.Open, FileAccess.Read, FileShare.None);
                RijndaelManaged RMCrypto = new RijndaelManaged();
                CryptoStream csEncrypt = new CryptoStream(fs, RMCrypto.CreateDecryptor(KEY, IV), CryptoStreamMode.Read);
                para = (Hashtable)formatter.Deserialize(csEncrypt);
                csEncrypt.Close();
                fs.Close();
            }
            catch (Exception e)
            {
                LogHelper.ErrorLog.AppendErrorMsg(e.ToString());
            }

            return para;
        }
    }
}
